package com.xmtlxx.web.controller.common;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.common.config.XmtlxxConfig;
import com.xmtlxx.common.constant.Constants;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.enums.CaptchaType;
import com.xmtlxx.common.sms.aliyun.AliyunSmsService;
import com.xmtlxx.common.sms.aliyun.SmsRequest;
import com.xmtlxx.common.sms.aliyun.SmsTemplateCode;
import com.xmtlxx.common.sms.aliyun.SmsTemplateParam;
import com.xmtlxx.common.sms.aliyun.config.AliyunConfig;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.redis.RedisUtils;
import com.xmtlxx.common.utils.reflect.ReflectUtils;
import com.xmtlxx.common.utils.spring.SpringUtils;
import com.xmtlxx.common.wxap.util.HttpInvokerUtils;
import com.xmtlxx.framework.config.properties.CaptchaProperties;
import com.xmtlxx.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author xmtlxx
 */
@Api(value = "验证码操作处理", tags = {"验证码管理"})
@RequiredArgsConstructor
@RestController
public class CaptchaController {

    private final CaptchaProperties captchaProperties;
    private final ISysConfigService configService;

    private final AliyunSmsService aliyunSmsService;

    /**
     * 生成验证码
     */
    @ApiOperation("生成验证码")
    @GetMapping("/captchaImage")
    public R<Map<String, Object>> getCode() {
        Map<String, Object> ajax = new HashMap<>();
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        //captchaOnOff = true;
        ajax.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff) {
            return R.ok(ajax);
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.setBackground(Color.WHITE);
        captcha.createCode();
        String code = isMath ? getCodeResult(captcha.getCode()) : captcha.getCode();
        RedisUtils.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        ajax.put("img", captcha.getImageBase64());
        ajax.put("result",code);
        return R.ok(ajax);
    }

    private String getCodeResult(String capStr) {
        int numberLength = captchaProperties.getNumberLength();
        int a = Convert.toInt(StringUtils.substring(capStr, 0, numberLength).trim());
        char operator = capStr.charAt(numberLength);
        int b = Convert.toInt(StringUtils.substring(capStr, numberLength + 1, numberLength + 1 + numberLength).trim());
        switch (operator) {
            case '*':
                return Convert.toStr(a * b);
            case '+':
                return Convert.toStr(a + b);
            case '-':
                return Convert.toStr(a - b);
            default:
                return StringUtils.EMPTY;
        }
    }

    @ApiOperation("生成验证码")
    @GetMapping("/getPhoneNumber")
    public R<String> getPhoneNumber(String phoneNumber){
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setTemplateCode(SmsTemplateCode.YC_VAILD_CODE.getSMS_CODE());
        smsRequest.setPhoneNumber(phoneNumber);
        SmsTemplateParam templateParam = new SmsTemplateParam();
        int number = new Random().nextInt(9000) + 1000;
        templateParam.setCode(number);
        RedisUtils.setCacheObject(phoneNumber, number+"", Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        smsRequest.setTemplateParam(templateParam);
        aliyunSmsService.AliyunSmsSend(smsRequest);
        return R.ok("发送成功");
//        SmsRequest smsRequest = new SmsRequest();
//        smsRequest.setAccessKeyId(AliyunConfig.accessKeyId);
//        smsRequest.setAccessKeySecret(AliyunConfig.accessKeySecret);
//        smsRequest.setPhoneNumber(phoneNumber);
//        smsRequest.setSignName(AliyunConfig.signName);
//        int number = ThreadLocalRandom.current().nextInt(100000000, 1000000000);
//        String code = "SMS_" + number;
//        String key = "phone" + phoneNumber;
//        smsRequest.setTemplateCode("验证码："+number+",您正在登陆安保云仓，该验证码5分钟内有效，请勿泄露于他人。");
////        SmsTemplateParam templateParam = new SmsTemplateParam();
////        templateParam.setOrderType("入库");
////        smsRequest.setTemplateParam(templateParam);
//        try {
//            RedisUtils.setCacheObject(key, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
//            Map<String,Object> data = new HashMap<>();
//            data.put("api","sms");
//            data.put("data",smsRequest);
//            String result = HttpInvokerUtils.PostToJson(XmtlxxConfig.getProtocol()+"://"+ XmtlxxConfig.getAliyunSmsEndpoint(), JsonUtils.toJsonString(data));
//            System.out.println("AliyunSmsSend===>"+result);
//            return R.ok();
//        }catch (Exception e){
//            e.printStackTrace();;
//            return R.fail();
//        }
    }

}
